import vuex from 'vuex'
import Vue from 'vue'
//取出存入的数据，初始化数据
let car=window.JSON.parse(localStorage.getItem('cart') || '[]')
Vue.use(vuex);
const storte =new vuex.Store({
    state:{
        totalcar:car
    },
    mutations:{
        addcar(state,cart){
            var foun=false;
            state.totalcar.forEach(item =>{
                
                if(item.id==cart.id){
                    item.number=item.number+cart.number;
                    foun=true;
                    return;
                }else{
                    foun=false;
                    return;
                }
            });  
            if(!foun){
                state.totalcar.push(cart);
            }
            localStorage.setItem("cart",window.JSON.stringify(state.totalcar));
        },
        setNumber(state,num){
            state.totalcar.forEach(item=>{
                if(item.id===num.id){
                    item.number=num.numb;
                }
            });
            localStorage.setItem("cart",window.JSON.stringify(state.totalcar));
        },
        stateChange(state,ss){
            state.totalcar.forEach(item=>{
                    if(item.id===ss.id){
                        console.log(ss.state);
                        item.state=ss.state
                }
                localStorage.setItem("cart",window.JSON.stringify(state.totalcar));
            })

        },
        delCart(state,id){
               state.totalcar.some((item,i)=>{
                        if(item.id==id){
                            state.totalcar.splice(i,1);
                            return true;
                        }
                })
               
                localStorage.setItem("cart",window.JSON.stringify(state.totalcar));
             
        }
    } ,
    getters:{
        getTotalCar(state){
            return state.totalcar;
        }
        ,getTotal(state){
            var total=0;
            if(state.totalcar){
                state.totalcar.forEach(item => {
                    total=total+item.number
                })
            }
            return total;
        },
        getIds(state){
        
        },
        shopTotal(state){
            var tt=0;
            state.totalcar.forEach(item=>{
                if(item.state){
                    tt=tt+item.number
                }
            })
            return tt;
        },
        totalPrice(state){
            var tp=0;
            state.totalcar.forEach(item=>{
                if(item.state){
                    tp=tp+item.number*item.money
                }
            })
            return tp;
        }
    }
    

}


);

export default storte;